<script>
	import LoginUtil from '@/main/common/LoginUtil.js'
	import constant from '@/common/constant.js'
	
	import TencentCloudChat from '@tencentcloud/chat';
	import { TUIChatKit, genTestUserSig } from "./TUIKit";
	import { TUILogin } from "@tencentcloud/tui-core";
	import IMUtil from '@/main/common/IMUtil.js';
	import RouteUtil from '@/main/common/RouteUtil.js';
	
	// IMUtil.init()
	uni.$chat_SDKAppID = constant.imApppId;
	uni.$chat_secretKey = constant.imSecretKey;
	uni.$TUIKit = TencentCloudChat.create({
		SDKAppID: uni.$chat_SDKAppID
	});
	//离线推送
	// uni.$TUIOfflinePush = uni.requireNativePlugin("TencentCloud-TUIOfflinePush");
	// console.warn(uni.$TUIOfflinePush, "TUIOfflinePush ｜ ok");
	

	export default {
		globalData: {
			webUrl: '',
			webTitle: '',
			chatUserId: '',
			chatTxCode: '',
			openTicketMin: false,
			ticketStartTime: 0,
			ticketTotalTime: 180,
			deviceModel: '',
			versionName: '',
		},
		onLaunch: function() {
			this.requestBaseUrl()
			uni.$online = constant.online;
			uni.getSystemInfo({
				success: (e) => {
					this.globalData.deviceModel = e.brand + '/' + e.deviceModel;
				}
			})
			// #ifdef APP-PLUS
			plus.runtime.getProperty(plus.runtime.appid, (info) => {
				this.versionName = info.version;
				this.globalData.versionName = info.version;
			});
			// #endif
			this.isLogin();
			this.loginIM();
		},

		methods: {
			requestBaseUrl() {
				uni.request({
					url: constant.baseUrl + '/api/white/reqAddress?',
					success: (res) => {
						if (200 == res.statusCode) {
							if(1==res.data.data.open){
								this.checkUpdate();
							}
						}
					}
				});
			},
			isLogin() {
				const login = uni.getStorageSync("login");
				if (!login) {
					// #ifdef APP-PLUS
					LoginUtil.loginOnce()
					// #endif
				}
				// #ifdef MP-WEIXIN
					this.wxLogin()
				// #endif
			},
			async wxLogin(){
				console.log("微信登录-开始")
				const openId = uni.getStorageSync('openId');
				console.log("openId:"+openId)
				if(openId){
					LoginUtil.wxLogin(openId);
				}else{
					this.getOpenId()
				}
			},
			getOpenId(){
				console.log("获取openId-开始")
				uni.login({
						"provider": "weixin",
						"onlyAuthorize": true, // 微信登录仅请求授权认证
						success: async (event) => {
							const { code } = event
							let url = constant.baseUrl+'/api/appWxLogin/loginWx?appName=zy&jsCode='+code;
							console.log("获取openId-code："+code)
							console.log("获取openId-url："+url)
							uni.request({
								url: url,
								success: (res) => {
									console.log('获得openId完成:' + JSON.stringify(res));
									if(res.data.data.openid){
										uni.setStorageSync('openId', res.data.data.openid);
										LoginUtil.wxLogin(res.data.data.openid);
									}
								}
							});
						},
					})
			},
			
			loginIM() {
				// IMUtil.login()
				const txCode = uni.getStorageSync("userTxCode");
				const token = uni.getStorageSync("token");
				if (txCode && token) {
					uni.$chat_userID = txCode + '';
					const config = {
						userID: uni.$chat_userID,
						SDKAppID: uni.$chat_SDKAppID,
						secretKey: uni.$chat_secretKey,
					}
					uni.$chat_userSig = genTestUserSig(config).userSig;
					TUIChatKit.init();
				
					const options = {
						SDKAppID: uni.$chat_SDKAppID,
						userID: uni.$chat_userID,
						userSig: uni.$chat_userSig,
						useUploadPlugin: true,
						framework: `vue2`,
					};
					//IM登录
					TUILogin.login(options).then(res => {
						console.log("IM登录成功：" + JSON.stringify(res));
						this.initUnReadMessage();
					}).catch(error => {
						console.log('IM登录失败:' + JSON.stringify(error));
					});
				}
			},
			initUnReadMessage() {
				//初始化未读消息
				setTimeout(()=>{
					uni.$TUIKit.getConversationList().then(res => {
						const unReadMessageCount = uni.$TUIKit.getTotalUnreadMessageCount();
						this.setUnReadMessageCount(unReadMessageCount);
					}).catch(error => {});
				}, 1000)
				
				//监听未读消息数
				uni.$TUIKit.on(TencentCloudChat.EVENT.TOTAL_UNREAD_MESSAGE_COUNT_UPDATED, event => {
					this.setUnReadMessageCount(event.data);
				});
			},
			setUnReadMessageCount(count) {
				if (count > 0) {
					uni.setTabBarBadge({
						index: constant.messageIndex,
						text: '' + count
					})
				} else {
					uni.removeTabBarBadge({
						index: constant.messageIndex
					})
				}
			},

			//检查更新
			checkUpdate() {
				// #ifdef APP-PLUS
				let urlstr = "https://zhiyuapp.oss-cn-fuzhou.aliyuncs.com/uniapp_android/poposeConfig-hw20240524.json?t=" + new Date().getTime();
				uni.request({
					url: urlstr,
					success: (res) => {
						uni.setStorageSync('vipManage', res.data.vipManage);
						uni.setStorageSync('ticketPrice', res.data.ticketPrice);
						uni.setStorageSync('isaliPay', res.data.isaliPay);
						if (res.data.ticketTime) {
							this.globalData.ticketTotalTime = res.data.ticketTime
						}
						console.log("线上版本: " + JSON.stringify(res.data.vss));
						console.log("本地版本: " + JSON.stringify(this.versionName));
						if (res.data.open == "1" && res.data.vss != this.versionName) {
							console.log("更新: ");
							this.install(res.data.wgtUrl);
						}else{
							console.log("不更新: ");
						}
					}
				})
				// #endif
			},

			//wgt下载安装
			install(wgtUrl) {
				// #ifdef APP-PLUS
				plus.downloader.createDownload(wgtUrl, {
					filename: "_doc/update/"
				}, (d, status) => {
					if (status == 200) {
						console.log("更新: 1111111");
						plus.runtime.install(d.filename, {
							force: true
						}, function() {
							console.log("更新: 33333");
							plus.nativeUI.closeWaiting();
							plus.runtime.restart();
						}, function(e) {
							console.log("更新: 444444");
							plus.nativeUI.closeWaiting();
						});
					} else {
						console.log("更新: 22222222");
						plus.nativeUI.closeWaiting();
					}
				}).start();
				// #endif
			},

			toTicket() {
				if (0 == this.globalData.ticketStartTime) {
					let timeId = setInterval(() => {
						console.log('ticket--start', this.globalData.ticketStartTime);
						this.globalData.ticketStartTime++
						if (this.globalData.ticketStartTime == this.globalData.ticketTotalTime) {
							clearInterval(timeId)
							uni.setStorageSync("ticketOver" + uni.getStorageSync('userId'), true)
							this.globalData.ticketStartTime = 0
							this.globalData.openTicketMin = true
							if(!uni.getStorageSync('vip')){
								RouteUtil.toRestartHome()
							}
						}
					}, 1000)
				}
			}

		}
	}
</script>

<style lang="scss">
	page {
		background-color: #f5f5f5;
	}
</style>